package com.party.course.controller;


import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.party.common.annotation.Log;
import com.party.common.core.controller.BaseController;
import com.party.common.core.domain.AjaxResult;
import com.party.common.enums.BusinessType;
import com.party.common.utils.StringUtils;
import com.party.common.utils.poi.ExcelUtil;
import com.party.course.domain.PlanClass;
import com.party.course.service.IplanClassService;
import com.party.course.service.impl.PlanClassServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.party.course.domain.SubAmountInfo;
import com.party.course.service.ISubAmountInfoService;
import com.party.common.core.page.TableDataInfo;

/**
 * 金额分账明细Controller
 *
 * @author ruoyi
 * @date 2025-06-06
 */
@RestController
@RequestMapping("/course/subAmount" )
public class SubAmountInfoController extends BaseController {
    @Autowired
    private ISubAmountInfoService subAmountInfoService;
    @Autowired
    private IplanClassService  planClassService;

/**
 * 查询金额分账明细列表
 */
//@RequiresPermissions("course:subAmount:list")
@GetMapping("/list" )
        public TableDataInfo list(SubAmountInfo subAmountInfo) {

        String planClassId = subAmountInfo.getPlanClassId();
        Boolean remove=false;
    Boolean update=false;
        if(StringUtils.isNotEmpty(planClassId)){
            PlanClass planclass = planClassService.getById(planClassId);
            String orderType = planclass.getOrderType();
            if("1".equals(orderType)){
                // 正式课
                String offFormal = planclass.getOffFormal();
                String offTest = planclass.getOffTest();
                if("0".equals(offFormal)  &&  !"0".equals(offTest)  ){
                    remove=true;
                }
                if("0".equals(offFormal)  &&  "0".equals(offTest) ){
                    update=true;


                }
            }
        }
        startPage();
        List<SubAmountInfo> list = subAmountInfoService.findList66(subAmountInfo);
        if (remove) {
            // 移除 list 中 role 为 1（可能有多条），中金额最低的那一条数据
            list.stream()
                    .filter(item -> "1".equals(item.getRole()))  // 筛选 role 为 "1" 的项
                    .min((o1, o2) -> o1.getProfitAmount().compareTo(o2.getProfitAmount()))  // 找到 profitAmount 最小的项
                    .ifPresent(list::remove);  // 如果存在，则从 list 中移除该项
        }
        if(update){
            // 修改 list 中 role 为 1（可能有多条），中金额最低的那一条数据的时间为加上30天
            list.stream()
                    .filter(item -> "1".equals(item.getRole()))  // 筛选 role 为 "1" 的项
                    .min((o1, o2) -> o1.getProfitAmount().compareTo(o2.getProfitAmount()))  // 找到 profitAmount 最小的项
                    .ifPresent(minItem -> {
                        // 假设时间字段名为 createTime，类型为 Date
                        // 如果是其他时间字段或类型，请相应调整
                        if (minItem.getCreateTime() != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(minItem.getCreateTime());
                            calendar.add(Calendar.DAY_OF_MONTH, 30);
                            minItem.setCreateTime(calendar.getTime());
                        }
                    });
        }
        return getDataTable(list);
    }

    @GetMapping("/getTotal" )
    public AjaxResult getTotal(SubAmountInfo subAmountInfo) {

        String planClassId = subAmountInfo.getPlanClassId();
        Boolean remove=false;
        if(StringUtils.isNotEmpty(planClassId)){
            PlanClass planclass = planClassService.getById(planClassId);
            String orderType = planclass.getOrderType();
            if("1".equals(orderType)){
                // 正式课
                String offFormal = planclass.getOffFormal();
                String offTest = planclass.getOffTest();
                if("0".equals(offFormal)  &&  !"0".equals(offTest)  ){
                    remove=true;
                }
            }
        }
        List<SubAmountInfo> list = subAmountInfoService.findList66(subAmountInfo);
        if (remove) {
            // 移除 list 中 role 为 1（可能有多条），中金额最低的那一条数据
            list.stream()
                    .filter(item -> "1".equals(item.getRole()))  // 筛选 role 为 "1" 的项
                    .min((o1, o2) -> o1.getProfitAmount().compareTo(o2.getProfitAmount()))  // 找到 profitAmount 最小的项
                    .ifPresent(list::remove);  // 如果存在，则从 list 中移除该项
        }
        //计算 list 中的profitAmount 的和
        BigDecimal total = list.stream().map(SubAmountInfo::getProfitAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        return AjaxResult.success(total);
    }


    /**
     * 导出金额分账明细列表
     */
    //@RequiresPermissions("course:subAmount:export")
    @Log(title = "金额分账明细" , businessType = BusinessType.EXPORT)
    @PostMapping("/export" )
    public void export(HttpServletResponse response, SubAmountInfo subAmountInfo) {
        List<SubAmountInfo> list = subAmountInfoService.findList66(subAmountInfo);
        ExcelUtil<SubAmountInfo> util = new ExcelUtil<SubAmountInfo>(SubAmountInfo. class);
        util.exportExcel(response, list, "金额分账明细数据" );
    }

    /**
     * 获取金额分账明细详细信息
     */
    //@RequiresPermissions("course:subAmount:query")
    @GetMapping(value = "/view/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) String id) {
        return AjaxResult.success(subAmountInfoService.view(id));
    }

    /**
     * 新增金额分账明细
     */
    //@RequiresPermissions("course:subAmount:add")
    @Log(title = "金额分账明细" , businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SubAmountInfo subAmountInfo) {
        subAmountInfoService.add(subAmountInfo);
        return AjaxResult.success("新增金额分账明细成功");
    }

    /**
     * 修改金额分账明细
     */
    //@RequiresPermissions("course:subAmount:edit")
    @Log(title = "金额分账明细" , businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody SubAmountInfo subAmountInfo) {
        return toAjax(subAmountInfoService.updateEntity(subAmountInfo));
    }

    /**
     * 删除金额分账明细
     */
    //@RequiresPermissions("course:subAmount:remove")
    @Log(title = "金额分账明细" , businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}" )
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(subAmountInfoService.deleteIds(Arrays.asList(ids)));
    }
}
